// 订单确认页
const app = getApp();

Page({
  data: {
    ticketId: null,
    scenicId: null,
    ticket: null,
    quantity: 1,
    useDate: '',
    totalAmount: '0.00',
    loading: false
  },

  onLoad(options) {
    if (options.ticketId) {
      this.setData({
        ticketId: parseInt(options.ticketId),
        scenicId: parseInt(options.scenicId || 0)
      });
      
      // 设置默认使用日期为明天
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      this.setData({
        useDate: this.formatDate(tomorrow)
      });
      
      this.loadTicketDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 加载门票详情
  loadTicketDetail() {
    wx.showLoading({
      title: '加载中',
    });
    
    wx.mRequest({
      url: `/api/ticket/${this.data.ticketId}`,
      method: 'GET',
      success: (res) => {
        wx.hideLoading();
        if (res.code === 0) {
          this.setData({
            ticket: res.data
          });
          // 计算初始总价
          this.calculateTotal();
        } else {
          wx.showToast({
            title: '加载门票信息失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 计算总价
  calculateTotal() {
    if (this.data.ticket && this.data.ticket.price) {
      const total = (this.data.ticket.price * this.data.quantity).toFixed(2);
      this.setData({
        totalAmount: total
      });
    }
  },
  
  // 数量减少
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      }, () => {
        this.calculateTotal();
      });
    }
  },
  
  // 数量增加
  increaseQuantity() {
    if (this.data.quantity < 10) {
      this.setData({
        quantity: this.data.quantity + 1
      }, () => {
        this.calculateTotal();
      });
    }
  },
  
  // 日期选择
  bindDateChange(e) {
    this.setData({
      useDate: e.detail.value
    });
  },
  
  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  
  // 提交订单
  submitOrder() {
    // 检查登录状态
    if (!app.checkLogin()) {
      wx.showModal({
        title: '提示',
        content: '请先登录再提交订单',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '用户信息不完整，请重新登录',
        icon: 'none'
      });
      return;
    }
    
    // 校验数据
    if (!this.data.ticket) {
      wx.showToast({
        title: '门票信息不存在',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.useDate) {
      wx.showToast({
        title: '请选择使用日期',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载
    wx.showLoading({
      title: '提交订单中...',
    });
    
    // 准备订单数据
    const orderData = {
      user: { id: userInfo.userId },
      productId: this.data.ticket.id,
      type: 1,  // 1-门票订单
      quantity: this.data.quantity,
      totalAmount: this.data.totalAmount,
      bookDate: this.formatDate(new Date()),
      useDate: this.data.useDate,
      status: 1  // 1-待支付
    };
    
    console.log('创建订单数据:', orderData);
    
    // 调用创建订单API
    wx.mRequest({
      url: '/api/order/create',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: orderData,
      success: (res) => {
        wx.hideLoading();
        console.log('创建订单响应:', res);
        
        if (res.code === 0) {
          wx.showToast({
            title: '预订成功',
            icon: 'success',
            duration: 2000
          });
          
          // 跳转到订单详情页
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order/order?tab=1'  // 1-待支付
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.msg || '预订失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('创建订单失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    });
  }
}); 